
function resetPage(){
	$('centerArea').update("").show();
	$('leftArea').update("").show();
	$('adminArea').update("").show();
	getLoginArea();

}



function showValue(){
	alert($('entity').value);
}

function insertSymbol(symbol){
	$('entity').value=symbol;
}

function getPos(){
	alert($('entity').selectionStart);
}

function insertAtCursor(myField, myValue) {
	  if ($(myField).selectionStart || $(myField).selectionStart == '0') {
	    var startPos = $(myField).selectionStart;
	    var endPos = $(myField).selectionEnd;
	    $(myField).value = $(myField).value.substring(0, startPos)
	                  + myValue
	                  + $(myField).value.substring(endPos, $(myField).value.length);
	   
	    //setting the caret position
	    if($(myField).setSelectionRange)
		{
	    	$(myField).focus();
	    	$(myField).setSelectionRange(startPos+1,startPos+1);
		}
		else if ($(myField).createTextRange) {
			var range = $(myField).createTextRange();
			$(myField).collapse(true);
			$(myField).moveEnd('character', startPos+1);
			$(myField).moveStart('character', startPos+1);
			$(myField).select();
		}
	  } else {
		  $('entity').value += myValue;
	  }
}

function setSelection(myField, location, length){
	//setting the caret position
    if($(myField).setSelectionRange)
	{
    	$(myField).focus();
    	$(myField).setSelectionRange(location,location+length);
	}
    
    else if ($(myField).createTextRange) {
		var range = $(myField).createTextRange();
		$(myField).collapse(true);
		$(myField).moveEnd('character', location);
		$(myField).moveStart('character', location+length);
		$(myField).select();
	}
    
}

function insertAtCursorAndUpdateStatus(myField, myValue, statusField) {
	  if ($(myField).selectionStart || $(myField).selectionStart == '0') {
		  $(statusField).update("").show();
		  var startPos = $(myField).selectionStart;
	    var endPos = $(myField).selectionEnd;
	    $(myField).value = $(myField).value.substring(0, startPos)
	                  + myValue
	                  + $(myField).value.substring(endPos, $(myField).value.length);
	    //$(myField).selectionStart=startPos+1;
	    //$(myField).selectionEnd=startPos+1;
	   
	    //setting the caret position
	    if($(myField).setSelectionRange)
		{
	    	$(myField).focus();
	    	$(myField).setSelectionRange(startPos+1,startPos+1);
		}
		else if ($(myField).createTextRange) {
			var range = $(myField).createTextRange();
			$(myField).collapse(true);
			$(myField).moveEnd('character', startPos+1);
			$(myField).moveStart('character', startPos+1);
			$(myField).select();
		}
	  } else {
		  $('entity').value += myValue;
	  }
}

function enterProblem(){
	new Ajax.Request( siteUrl + 'problem.php', {
		parameters: {action: 'getProblemArea'},		
		onSuccess: function( response ) {
			if(response.responseText == "LoggedOut"){
				resetPage();
			} else {
				$('centerArea').update( response.responseText ).show();
			}
		},
		onFailure: function( response ) {
			$('centerArea').update( 'Unknown error.' ).show();
		}
	});
}

function removeSpaces(str) {
	var lookFor=" ";
	var replaceWith ="";
	 str = str.replace(/ /g,replaceWith);
	 return str.trim();
}


//compares the entered answer with the correct answer(s) and checks the syntax
function checkAnswer(questionId){
	var myField = 'entity'+questionId; 
	var vastus = removeSpaces($(myField).value);
	 var questionId = questionId;
	 if(vastus.length==0){
		 alert("Sisesta midagigi");
	 } else{
	 var oigeVastus1 = "";
	 var oigeVastus2 = "";
	 var oigeVastus3 = "";
	 var argumendid = new Array();
	 
	 // assesses syntax + save answer if syntax is correct
	 new Ajax.Request( siteUrl + 'problem.php', {
			parameters: {action: 'getCorrect', question: questionId},
			onSuccess: function( response ) {
				if(response.responseText == "LoggedOut"){
					resetPage();
				} else {
				
					argumendid = response.responseText;
					var verdict = assessor(vastus, argumendid, myField);
					switch (verdict)
					{
						case "OK":
							// save the answer if the syntax is correct
							new Ajax.Request( siteUrl + 'results.php', {
								parameters: {action: 'insertAnswer',
									vastus: vastus, ulesanneId: questionId},
								onSuccess: function( response ) {
									var json = response.responseText.evalJSON();
									if(json.testStatus!="Closed"){
										$('answerStatus'+questionId).update( "Vastatud: "+vastus).show();
										if(json.decision == "OK"){
											alert("Õige vastus. Tubli.");
										}
									} else {
										alert("Aeg läbi");
										loadOpenTests();
									}
									
								},
								onFailure: function( response ) {
									alert("Ei saanud salvestada");
								}
							});
							break;
						
							
							
						default:
						  alert(verdict);
					}
				}

			},
			onFailure: function( response ) {
				alert("Ei saanud serverist oiget vastust");
			}
		});
	 
}};

function saveAnswer(answer){
	new Ajax.Request( siteUrl + 'problem.php', {
		parameters: {action: 'getProblemArea'},		
		onSuccess: function( response ) {
			if(response.responseText == "LoggedOut"){
				resetPage();
			} else {
				$('centerArea').update( response.responseText ).show();
			}
		},
		onFailure: function( response ) {
			$('centerArea').update( 'Unknown error.' ).show();
		}
	});
}


// assesses students answer
// returns verdict
function assessor(answer, argument, myField){
	
	
	
	var answer = answer;
	
	if(answer.length==0){
		return "OK";
	}
	
	var argument = argument.replace(/,/g,'');
	var kvantorid= "∀,∃,¬";
	var sulud = "(,),{,},[,]";
	
	
	//keeps track of whih arguments have appeared 
	var appearedArguments = "";
	
	//signatuur naturaalarvude hulgal
	var signatuur = '0,1,+,*,=,';
	
	//keeps an array of boundvariables
	var boundVariables = new Array();
	
	var lubatudKarakterid = signatuur+"&,⋁,⊃"+argument+","+kvantorid+","+sulud;
	lubatudKarakterid = lubatudKarakterid.replace(/,/g,'');
	//alert(lubatudKarakterid);
	var al = answer.length;
	
	
	//check parnethesis completeness
	if(!parCheck(answer)){
		return "Sulud pole korras";
	}

	var temp = "";
	var binder = new Array();
	var next = "";
	if(!isNextValid("start", answer.charAt(0), argument)){
		return "Viga: mittesobiv algus";
	}
	
	//Igasuguste kontrollide kasutamine
	for (var s = 0; s < al;s++){
		//liigsete vordusmarkide otsimine
		if(answer.charAt(s)=="="){
			var errorLocation = eqAmountCheck(answer, s);
			if(errorLocation!=0){
				setSelection(myField, errorLocation, 1);
				return "Liigne võrdusmärk kohas: "+(errorLocation+1);
			}
		}
		//&V ning implikatsiooni vasakul ja paremal asuva avaldise kontroll (kas need avaldised voivad seal olla)
		if(answer.charAt(s)=='⊃' || answer.charAt(s)=='&' || answer.charAt(s)=='⋁'){
			if(!parContentChecker(answer, s)){
				setSelection(myField, s, 1);
				return "Operaatori "+answer.charAt(s)+", mis asub kohas "+(s+1)+" pool(ed) pole korras";
			}
		}
		
		if(answer.charAt(s)=="¬"){
			if(answer.charAt(s+1)=="¬"){
				setSelection(myField, s, 2);
				return "Topelteitus. Ebaotstarbekas.";
			}
			if(!notParContentChecker(answer, s)){
				setSelection(myField, s, 1);
				return "Operaatorile ¬ kohas "+(s+1)+" järgnevate sulgude sisu pole süntaktiliselt korrektne";
			}
		}
	}
	
	//signatuurile vastavuse kontrollimine
	for (var l = 0; l < al;l++){
		temp = answer.charAt(l);
		
		if(temp == ','){
			setSelection(myField, l, 1);
			return "Mittesobiv sümbol \",\" kohas: "+(l+1);
		}
		
		// if the char is the last one, change next to "_" which represents end
		if( l <= al-1 ){
			next = muutuja = answer.charAt(l+1);
		} else if(temp.match(/^[a-z A-Z]+$/) && argument.indexOf(temp)==-1){
			return "Mittesobiv sümbol valemi lopus";
			}else next = "_";
		
		//records appearances of arguments
		if(argument.indexOf(temp)!=-1){
			//alert("leitud argument: "+temp);
			if(appearedArguments.indexOf(temp)==-1){
				appearedArguments += temp;
				//alert("ilmunud: "+appearedArguments);
			}
		}

		if(temp == '+' || temp == '*'){
			var m = formulaCompletenessCheck(answer, l);
			switch(m)
				{
				case "OK":
				  break;
				default:
					setSelection(myField, l, 1);
					return m;
					break;
				}
		}
		
		//seotud muutujate leidmine ning nende objektide loomine
		if(temp == '∀' || temp == '∃' ){
				var muutuja = l+1;
				muutuja = answer.charAt(muutuja);
				
				var boundArgument = false;
				
				//argument ei tohi olla seotud
				for(var a = 0; a<argument.length;a++){		
					
					if(argument[a]==muutuja){
						boundArgument= true;
					}
				}
				
				if(boundArgument){
					setSelection(myField, l+1, 1);
					return "Argument ei tohi olla seotud";
				}
				
				
				if(muutuja.match( /^[a-z A-Z]+$/)){
					//kontroll, ega kvantor vales kohas ei ole
					if( l <= al-5 ){				
						var rangeStart = 0;
						var rangeEnd = 0;
						
						//vasak- ja parempoolsete sulgude arv
						var openPar = 0;
						var closePar = 0;
						var exists = false;
						var boundVariable = answer.charAt(l+1);
						
						//vahemike leidmine kus seotud muutujad olla voivad
						for(var start = l+2;start<al;start++){
							if(answer.charAt(start)=='('){
								openPar++;
								if(rangeStart == 0 ){
									rangeStart = start;
									}
								}
							if(answer.charAt(start)==')'){
								closePar++;
								if(openPar == closePar ){
									rangeEnd = start;
									break;
									}
								}
							if(answer.charAt(start)==boundVariable){
								exists = true;
								}
							}
						if(exists){
							for(var b = 0;b<binder.length;b++){
								if(muutuja == binder[b].symbol){
									if(rangeStart == binder[b].rangeStart){
										setSelection(myField, l+1, 1);
										return "Muutuja \""+muutuja+"\" on samas mõjualas seotud kahe kvantoriga";
									}
									
								}
							}
							
							binder[binder.length]= new variable(muutuja, rangeStart,
									rangeEnd, l+1);
							} else {
								setSelection(myField, l+1, 1);
								return "Kvantoriga seotud muutuja ei esine kvantori mõjupiirkonnas";
							}
						
					} else {
						setSelection(myField, l, 1);
						return "Kvantori järelt vajalikud liikmed puudu";	
					}
				} else {
					setSelection(myField, l+1, 1);
					return "Kvantorile peab järgnema muutuja";
				}
		} else {
			
			if(l>0){
				
				if(l==al-1){
					if(!isNextValid(temp, "_", argument)){
						return "Ei sobi loppu: "+temp;
					}
				} else
				
				if(answer.charAt(l-1)== '∀' || answer.charAt(l-1) == '∃' ){
					if(!isNextValid("muutuja_peale_kvantorit", answer.charAt(l+1), argument)){
						setSelection(myField, l, 1);
						return "Mittesobiv kombinatsioon: \""+temp+""+answer.charAt(l+1)+"\" kohas "+(l+1);
					}
				} else if(!isNextValid(temp, answer.charAt(l+1), argument)){
					setSelection(myField, l, 2);
					return "Mittesobiv kombinatsioon: \""+temp+""+answer.charAt(l+1)+"\" kohas "+(l+1);
				}
			} else {
				if(!isNextValid(temp, answer.charAt(l+1), argument)){
					setSelection(myField, l, 2);
					return "Mittesobiv kombinatsioon: \""+temp+""+answer.charAt(l+1)+"\" kohas "+(l+1);
				}
			}
		}
		
		//kontroll, kas kõik sumbolid on lubatud
		if(lubatudKarakterid.indexOf(temp)==-1){
			//kui ei ole, siis kas on kvantoriga seotud
			var allowed = false;
			for(var seo = 0; seo<binder.length;seo++){
				var comp = binder[seo].symbol == temp;
				if(comp){
					if(l < binder[seo].rangeEnd){
						if(l > binder[seo].rangeStart) allowed = true;
						if(l == binder[seo].definedAt) allowed = true;
					}
				}
			}
			//kui sumbol ei ole signatuuris, argumentides ega kvantoriga seotud
			if(!allowed){
				setSelection(myField, l, 1);
				return "Mittesobiv sümbol: "+temp+" kohas"+(l+1);
			}
		}
	}
	
	//kas etteantud argumente ja leitud argumente on sama palju
	if(appearedArguments.length!=argument.length){
		return "Valemis ei leidu koik argumendid"
	}
	
	
	return "OK";
}

/**
 * 
 * @param character- the character
 * @param followers- string of characters that is allowed to follow this character
 * @param argumentsallowed- are arguments allowed to follow this character
 */
function followers(followers, argumentsallowed){
	this.followers = followers;
	this.argumentsAllowed = argumentsallowed;
}

//these do not include arguments
var allowedFollowersList = new Array();
allowedFollowersList["∀"]= new followers( "abcdefghijklmnopqrstuvxyz", false);
allowedFollowersList["∃"]= new followers( "abcdefghijklmnopqrstuvxyz", false);
allowedFollowersList["0"]= new followers( "*+)_=", false);
allowedFollowersList["1"]= new followers( "*+)_=", false);
allowedFollowersList["="]= new followers( "abcdefghijklmnopqrstuvxyz01(", true);
allowedFollowersList["&"]= new followers( "∀∃¬(", false);
allowedFollowersList["⋁"]= new followers( "∀∃¬(", false);
allowedFollowersList["¬"]= new followers( "∀∃(", false);
allowedFollowersList["⊃"]= new followers( "¬∀∃(", false);
allowedFollowersList["("]= new followers( "¬∀∃(01abcdefghijklmnopqrstuvxyz", true);
allowedFollowersList[")"]= new followers( ")⊃&⋁_+*=", false);
allowedFollowersList["start"]= new followers( "¬∀∃(01", true);
allowedFollowersList["+"]= new followers( "01abcdefghijklmnopqrstuvxyz(", true);
allowedFollowersList["*"]= new followers( "01abcdefghijklmnopqrstuvxyz(", true);
//seotud muutuja
allowedFollowersList["muutuja"]= new followers( "+*)=", true);
//seotud muutuja peale kvantorit(muutuja sidumine)
allowedFollowersList["muutuja_peale_kvantorit"]= new followers( "∀∃¬(⊃", true);
allowedFollowersList["argument"] = new followers("+*)=_",false);



/**
 * Tests if the next character is allowed to follow the current one
 * 
 * @param current- current character
 * @param next- next character
 * @param arguments- set of characters
 * @param binder- true/false- is the character behind a quantor
 * @return true/false
 */
function isNextValid(current, next, arguments){
	var current = current;
	var next = next;
	var arguments = arguments;
	//alert("jouab sisse: "+current+" ja "+next+"");
	var alfabeet = "abcdefghijklmnopqrstuvxyz";
	
	if(current.length==1){
		if(alfabeet.indexOf(current)!=-1){
			if(arguments.indexOf(current)!=-1){
				current = "argument";
			} else current = "muutuja";
		}
	}
	
	//allow arguments at the beginning
	if(current == "start"){
		if(arguments.indexOf(next)!=-1){
			return true;
		}
	}
	
	if(allowedFollowersList[current].followers.indexOf(next)!=-1){
		if(arguments.indexOf(next)!=-1){
			if(!allowedFollowersList[current].argumentsAllowed){
				return false;
			} else return true;
			
		} else return true;

	} else return false;

}


//TODO
/**
 * Used when operators such as &V are present
 * Both sides of &V have to be equations
 * 
 * @param answer- string answer
 * @param currentPos- number
 * @returns true/false depending on whether the content of parenthesis is correct or not
 */
function parContentChecker(formula, currentPos){
	var formula = formula;
	var currentPos = currentPos;
	//left border of the leftside parenthesis
	var leftStart = 0;
	var leftEnd = 0;
	//right border of the right side parenthesis
	var rightStart = 0;
	var rightEnd = 0;
	
	var openP = 0;
	var closeP = 0;
	
	//get the left side equations border
	for(var lefty = currentPos; lefty >= 0 ;lefty--){
		if(formula.charAt(lefty)==")"){
			if(closeP == 0){
				leftEnd = lefty;
			}	
			closeP++;
		}
		if(formula.charAt(lefty)=="("){
			openP++;
		}
		if(closeP==openP && closeP!=0 ){
			leftStart = lefty;
			break;
		}
	}
	
	var openP = 0;
	var closeP = 0;
	
	//get the right side equations border
	for(var righty = currentPos; righty <formula.length ; righty++){
		if(formula.charAt(righty)==")"){	
			closeP++;
		}
		if(formula.charAt(righty)=="("){
			if(openP == 0){
				rightStart = righty;
			}
			openP++;
		}
		if(closeP==openP && closeP!=0){
			rightEnd = righty;
			break;
		}
	}
	
	
	//get the equations
	var leftEq= formula.substring(leftStart+1, leftEnd);
	var rightEq= formula.substring(rightStart+1, rightEnd);
	
	var leftOk = false;
	var rightOk = false;
	
	//process the equations
	for(var lc = 0; lc < leftEq.length; lc++){
		if(leftEq.charAt(lc)=='⊃' || leftEq.charAt(lc)=='&' || leftEq.charAt(lc)=='⋁'){
			if(!parContentChecker(leftEq, lc)){
				return false;
			}
			leftOk = true;
		}
		if(leftEq.charAt(lc)=='¬'){
			if(!notParContentChecker(leftEq, lc)){
				return false;
			}
		}
		if(leftEq.charAt(lc)=="="){
			leftOk = true;
		}
	}
	for(var rc = 0; rc < rightEq.length; rc++){
		if(rightEq.charAt(rc)=='⊃' || rightEq.charAt(rc)=='&' || rightEq.charAt(rc)=='⋁'){
			if(!parContentChecker(rightEq, rc)){
				return false;
			}
		}
		if(rightEq.charAt(rc)=='¬'){
			if(!notParContentChecker(rightEq, rc)){
				return false;
			}
		}
		if(rightEq.charAt(rc)=="="){
			rightOk = true;
		}
	}
	if(rightOk && leftOk){
		return true;
	} else return false;;

}

/**
 * Used when operator ¬ is present
 * 
 * @param answer- string answer
 * @param currentPos- number
 * @returns true/false depending on whether the content of parenthesis is correct or not
 */
function notParContentChecker(formula, currentPos){
	var formula = formula;
	var currentPos = currentPos;
	//right border of the right side parenthesis
	var rightStart = 0;
	var rightEnd = 0;
	
	var openP = 0;
	var closeP = 0;
	
	//get the right side equations border
	for(var righty = currentPos; righty <formula.length ; righty++){
		if(formula.charAt(righty)==")"){	
			closeP++;
		}
		if(formula.charAt(righty)=="("){
			if(openP == 0){
				rightStart = righty;
			}
			openP++;
		}
		if(closeP==openP && closeP!=0){
			rightEnd = righty;
			break;
		}
	}
	
	
	//get the equation
	var rightEq= formula.substring(rightStart+1, rightEnd);
	var rightOk = false;
	
	//process the equations
	for(var rc = 0; rc < rightEq.length; rc++){
		if(rightEq.charAt(rc)=='⊃' || rightEq.charAt(rc)=='&' || rightEq.charAt(rc)=='⋁'){
			if(!parContentChecker(rightEq, rc)){
				//alert("leitud viga paremas pooles");
				return false;
			}
		}
		if(rightEq.charAt(rc)=='¬'){
			if(!notParContentChecker(rightEq, rc)){
				//alert("leitud viga paremas pooles");
				return false;
			}
		}
		if(rightEq.charAt(rc)=="="){
			rightOk = true;
		}
	}
	
	//alert("p: "+rightEq);
	if(rightOk){
		return true;//alert(" eituse parem pool korras");
	} else return false; //alert("eituse parem pool pole korras");

}



/*
 * makes sure that if a + or * exists then there is a = aswell
 * 
 */
function formulaCompletenessCheck(answer, location){
	var answer = answer;
	var location = location;
	var eqExists = false;

	
	for(var g = location;g<answer.length;g++){
		//alert("VordusP?: "+answer.charAt(g));
		if(answer.charAt(g)=='∀' || answer.charAt(g)=='∃' || answer.charAt(g)=='¬' || answer.charAt(g)=='⊃' || answer.charAt(g)=='&' || answer.charAt(g)=='⋁'){
			break;
		} else if(answer.charAt(g)=="="){
			if(!eqExists){
				eqExists = true;
			} else return "Liigne võrdusmärk kohas "+g;
		}
	}
	
	for(var p = location;p>0;p--){
		//alert("VordusL?: "+answer.charAt(p));
		if(answer.charAt(p)=='∀' || answer.charAt(p)=='∃' || answer.charAt(p)=='¬' || answer.charAt(p)=='⊃' || answer.charAt(p)=='&' || answer.charAt(p)=='⋁'){
			break;
		} else if(answer.charAt(p)=="="){
			if(!eqExists){
				eqExists = true;
			} else return "Liigne võrdusmärk kohas "+p;
		}
	}
	if(eqExists){
		return "OK";
	} else {
		return "Sümbol "+answer.charAt(location)+" kohas "+location+" vajab võrdusmärki";
	}
	
}

/**
 * Checks number of equation symbols in element of formula. If additional =-s are found,
 * false is returned 
 * @param answer- string
 * @param location- number
 * @return location of excess =. 0 if no excess =-s were found.
 */
function eqAmountCheck(answer, location){
	var answer = answer;
	var location = location;
	var eqCount = 1;
	
	//to the right
	for(var e = location+1; e < answer.length;e++){
		if(answer.charAt(e)=="="){
			return e;
			break;
		}
		if(answer.charAt(e)=="⋁" || answer.charAt(e)=="∃" || answer.charAt(e)=="∀" || answer.charAt(e)=="&" || answer.charAt(e)=="⊃"){
			break;
		}
	}
	return 0;
	
}


//inserting or editing a question
function insertProblem(testId){
	var id = testId;
	var vastus = removeSpaces($('correctAnswer1').value);
	var vastus2 = removeSpaces($('correctAnswer2').value);
	var vastus3 = removeSpaces($('correctAnswer3').value);
	var argumendid = $('arguments').value;
	var kirjeldus = Encoder.htmlEncode($('kirjeldus').value);
	var punktid = $('points').value;
	if(vastus.length==0){
	 alert("Vastus tühi");
	} else { 
		if(argumendid.length==0){
		alert("Argumente pole")
		} else {
			var decision = assessor(vastus, argumendid, 'correctAnswer1');
			var decision2 = assessor(vastus2, argumendid, 'correctAnswer1');
			var decision3 = assessor(vastus3, argumendid, 'correctAnswer1');
			if(decision=="OK" && decision2 == "OK" && decision3 == "OK"){
				 new Ajax.Request( siteUrl + 'problem.php', {
						parameters: {action: 'insertProblem', vastus: vastus, vastus2: vastus2,
							vastus3: vastus3,
							argumendid: argumendid, kirjeldus: kirjeldus, testId: id,
							punktid: punktid 
							},
						onSuccess: function( response ) {
							if(response.responseText == "LoggedOut"){
								resetPage();
							} else {
								alert("Ülesanne sisestatud");
								new Ajax.Request( siteUrl + 'modules.php?action=questionAdder&testId='+id, {
									onSuccess: function( response ) {
										if(response.responseText == "LoggedOut"){
											resetPage();
										} else {
											$('centerArea').update( response.responseText ).show();
										}
									},
									onFailure: function( response ) {
										alert("Failure");
									}
								});
							}
							},
						onFailure: function( response ) {
							$('centerArea').update( 'Unknown error.' ).show();
						}
					});
			} else if(decision=="OK"){
						if(decision2=="OK"){
							if(decision3=="OK"){
								} else alert("Viga vastuses 3: "+decision3);
							} else alert("Viga vastuses 2: "+decision2);
					} else alert("Viga vastuses 1: "+decision); 
		
		}
	}
}

//syntax check for the question editor
/**
 * questionId- which question
 * answerNr- which answer (1,2,3)
 * 
 */
function assessSyntax(questionId, answerNr){
	var questionId = questionId;
	var vastus = removeSpaces($('entity'+answerNr+"_"+questionId).value);
	var argumendid = removeSpaces($('arguments'+questionId).value);
	var assessment = assessor(vastus, argumendid, 'entity'+answerNr+"_"+questionId);
	switch (assessment)
	{
		case "OK":
			$('answerStatus'+answerNr+"_"+questionId).update("Süntaks korras").show();
			break;
		default:
			alert(assessment);
			break;
	}
	
}

function emptyStatus(questionId, answerNr){
	var questionId = questionId;
	var answerNr = answerNr;
	$('answerStatus'+answerNr+"_"+questionId).update("").show();
}

//inserting or editing a question
function editProblem(questionId){
	var id = questionId;
	var vastus = removeSpaces($('entity1_'+questionId).value);
	var vastus2 = removeSpaces($('entity2_'+questionId).value);
	var vastus3 = removeSpaces($('entity3_'+questionId).value);
	var argumendid = $('arguments'+id).value;
	var kirjeldus = Encoder.htmlEncode($('description'+questionId).value);
	var punktid = $('points'+questionId).value;
	
	if( vastus == '' && vastus == '' && vastus == '') {
		alert("Sisesta vastus");
		return;
	}
	if( argumendid == '' || ( argumendid.lenght==0 && !argumendid.match(/^[a-z A-Z]+$/))) {
		alert("Sisesta argumendid");
		return;
	}

	
	new Ajax.Request( siteUrl + 'problem.php', {
		parameters: {action: 'alterProblem', question: questionId,
			answer1: vastus, answer2: vastus2,
			answer3: vastus3, arguments: argumendid,
			description: kirjeldus, points: punktid},
		onSuccess: function( response ) {
			if(response.responseText == "LoggedOut"){
				resetPage();
			} else {
				if(response.responseText == "OK"){
					alert("Muudatused salvestatud");
				}else alert(response.responseText);
			}
		},
		onFailure: function( response ) {
			alert("Viga. Muudatusi ei salvestatud");
		}
	});
	
}
//inserting or editing a question
function removeProblem(questionId, testId){
	var id = questionId;
	new Ajax.Request( siteUrl + 'problem.php', {
		parameters: {action: 'removeProblem', question: questionId},
		onSuccess: function( response ) {
			if(response.responseText == "LoggedOut"){
				resetPage();
			} else {
				if(response.responseText == "OK"){
					listQuestions(testId);
				}else alert(response.responseText);
			}
		},
		onFailure: function( response ) {
			alert("Viga. Ei saa hetkel kustutada. Proovi hiljem uuesti.");
		}
	});
	
}


//checks if all parenthesis are complete 
function parCheck(vastus){
	var open = 0;
	var close = 0;
	
	for(var s = 0; s<vastus.length;s++ ){
		if(vastus.charAt(s)=='('){
			open++;
			}
		if(vastus.charAt(s)==')'){
			close++;
			}
	}
	
	if(open == close){
		return true;
	} else return false;
	
}

//seotud muutujate objekt
function variable(symbol, rangeStart, rangeEnd, definedAt){
	this.symbol = symbol;
	this.definedAt = definedAt;
	this.rangeStart = rangeStart;
	this.rangeEnd = rangeEnd;

}

function getSymbols(string){
	var concatenated = string;
	var symbols=new Array();
	symbols = concatenated.split(",");
	return symbols;
};